﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using VOL.demo.IRepositories.ShopOrder;
using VOL.demo.IServices.wms.ShopOrder;
using VOL.Entity.DomainModels;

namespace VOL.demo.Services.wms.ShopOrder
{
    public class ShopOrderService : IShopOrderService
    {
        private readonly IShopOrderRepository _repository;

        public ShopOrderService(IShopOrderRepository repository)
        {
            _repository = repository;
        }

        /// <summary>
        /// 分页查询销售订单
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页记录数</param>
        /// <param name="whereExpression">查询条件</param>
        /// <returns>分页结果</returns>
        public async Task<(List<shopordermodel> Data, int TotalCount)> GetPageListAsync(int pageIndex, int pageSize,
            Expression<Func<shopordermodel, bool>> whereExpression = null)
        {
            // 页码从1开始，但SqlSugar分页从0开始，需要转换
            int sqlSugarPageIndex = pageIndex <= 0 ? 0 : pageIndex - 1;

            return await _repository.GetPageListAsync(sqlSugarPageIndex, pageSize, whereExpression);
        }

        /// <summary>
        /// 分页查询销售订单联查结果（包含客户名称、部门名称、用户名称）
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页记录数</param>
        /// <param name="shopOrderCode">销售单号（可选）</param>
        /// <param name="shopOrderDate">销售日期（可选）</param>
        /// <returns>分页结果</returns>
        public async Task<(List<ShopOrderDto> Data, int TotalCount)> GetPageListWithRelationsAsync(
            int pageIndex,
            int pageSize,
            string shopOrderCode = null,
            DateTime? shopOrderDate = null)
        {
            // 页码从1开始，但SqlSugar分页从0开始，需要转换
            int sqlSugarPageIndex = pageIndex <= 0 ? 0 : pageIndex - 1;

            return await _repository.GetPageListWithRelationsAsync(sqlSugarPageIndex, pageSize, shopOrderCode, shopOrderDate);
        }

        /// <summary>
        /// 根据ID获取销售订单
        /// </summary>
        /// <param name="id">销售订单ID</param>
        /// <returns>销售订单信息</returns>
        public async Task<shopordermodel> GetByIdAsync(long id)
        {
            return await _repository.GetByIdAsync(id);
        }

        /// <summary>
        /// 更新销售订单
        /// </summary>
        /// <param name="entity">销售订单实体</param>
        /// <returns>更新结果</returns>
        public async Task<bool> UpdateAsync(shopordermodel entity)
        {
            // 更新前进行数据验证
            if (entity == null)
            {
                return false;
            }

            // 设置修改时间和修改人信息
            entity.ModifyDate = DateTime.Now;

            // 可以在这里添加其他业务逻辑，例如验证状态等

            return await _repository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除销售订单
        /// </summary>
        /// <param name="id">销售订单ID</param>
        /// <returns>删除结果</returns>
        public async Task<bool> DeleteAsync(long id)
        {
            // 删除前可以进行业务验证，例如检查是否有关联数据
            var entity = await _repository.GetByIdAsync(id);
            if (entity == null)
            {
                return false;
            }

            // 可以在这里添加其他业务逻辑，例如验证状态是否允许删除
            // 例如：已审核的订单不允许删除
            if (entity.Status > 1)
            {
                // 这里可以抛出异常或返回false
                return false;
            }

            return await _repository.DeleteAsync(id);
        }

        /// <summary>
        /// 批量删除销售订单
        /// </summary>
        /// <param name="ids">销售订单ID列表</param>
        /// <returns>删除结果</returns>
        public async Task<bool> DeleteRangeAsync(long[] ids)
        {
            if (ids == null || ids.Length == 0)
            {
                return false;
            }

            // 可以在这里添加批量删除前的业务验证逻辑
            // 例如：检查这些订单是否都允许删除

            return await _repository.DeleteRangeAsync(ids);
        }

        /// <summary>
        /// 获取货品分页列表
        /// </summary>
        public async Task<(List<ProductDisplayDto> Data, int TotalCount)> GetProductPageListAsync(ProductSearchDto searchDto)
        {
            return await _repository.GetProductPageListAsync(searchDto);
        }

        /// <summary>
        /// 获取部门级联列表
        /// </summary>
        public async Task<List<DepartmentCascadeDto>> GetDepartmentCascadeListAsync(DepartmentSearchDto searchDto)
        {
            return await _repository.GetDepartmentCascadeListAsync(searchDto);
        }

        /// <summary>
        /// 获取用户下拉选择列表
        /// </summary>
        public async Task<(List<UserSelectDto> Data, int TotalCount)> GetUserSelectListAsync(UserSearchDto searchDto)
        {
            return await _repository.GetUserSelectListAsync(searchDto);
        }

        /// <summary>
        /// 添加销售订单和销售订单明细（使用事务，自动设置系统字段）
        /// </summary>
        public async Task<bool> AddWithDetailsAsync(ShopOrderWithDetailsCreateDto createDto)
        {
            try
            {
                Console.WriteLine("=== Service层开始处理销售订单添加 ===");
                Console.WriteLine($"createDto是否为null: {createDto == null}");
                
                if (createDto == null)
                {
                    Console.WriteLine("❌ 失败原因: createDto为null");
                    throw new ArgumentNullException(nameof(createDto), "销售订单创建数据不能为空");
                }
                
                if (createDto.ShopOrder == null)
                {
                    Console.WriteLine("❌ 失败原因: ShopOrder为null");
                    throw new ArgumentException("销售订单信息不能为空", nameof(createDto.ShopOrder));
                }
                
                if (createDto.ShopOrderDetails == null || !createDto.ShopOrderDetails.Any())
                {
                    Console.WriteLine("❌ 失败原因: ShopOrderDetails为空");
                    throw new ArgumentException("销售订单明细不能为空", nameof(createDto.ShopOrderDetails));
                }

                // 这里可以添加业务逻辑验证
                // 例如：检查销售订单编号是否重复
                // 例如：验证客户是否存在
                // 例如：验证货品是否存在
                // 例如：计算总金额是否正确

                Console.WriteLine("✅ Service验证通过，调用Repository");
                var result = await _repository.AddWithDetailsAsync(createDto);
                Console.WriteLine($"Repository返回结果: {result}");
                
                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ Service层异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                throw; // 重新抛出异常，让Controller层处理
            }
        }

        /// <summary>
        /// 获取所有客户简单列表（仅ID和名称）
        /// </summary>
        public async Task<List<CustomerSimpleDto>> GetAllCustomersSimpleAsync()
        {
            return await _repository.GetAllCustomersSimpleAsync();
        }
    }
}
